package com.bishe.demo.modules.account.dao;

import com.bishe.demo.modules.account.entity.Resource;
import com.bishe.demo.modules.common.entity.SearchBean;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface ResourceDao {
    @Insert("insert into account_resource values(null,#{permission})")
    @Options(useGeneratedKeys = true, keyColumn = "resource_id", keyProperty = "resourceId")
    void insertResource(Resource resource);

    @Update("update account_resource set permission=#{permission} where resource_id=#{resourceId}")
    void updateResource(Resource resource);

    @Delete("delete from account_resource where resource_id=#{resourceId}")
    void deleteResourceByResourceId(int resourceId);

    @Select("select * from account_resource where resource_id = #{resourceId}")
    @Results(id = "resourceResult", value = {
            @Result(column = "resource_id", property = "resourceId"),
            @Result(column = "resource_id", property = "roles",
                    javaType = List.class,
                    many = @Many(select = "com.bishe.demo.modules.account.dao.RoleDao.getRolesByResourceId"))
    })
    Resource getResourceByResourceId(int resourceId);

    @Select("select * from account_resource ar left join account_role_resource arr on ar.resource_id = arr.resource_id where arr.role_id = #{roleId}")
    List<Resource> getResourcesByRoleId(int roleId);

    @Select("<script>"
            + "select * from account_resource "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (permission like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by resource_id asc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<Resource> getResourcesBySearchBean(SearchBean searchBean);
}
